# Copyright 2023 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""A simple LLM agent."""
import collections
import functools
from typing import override

from concordia.language_model import language_model
from concordia.typing.deprecated import agent
from concordia.typing.deprecated import entity

# TODO: b/313715068 - remove disable once pytype bug is fixed.
# pytype: disable=override-error


class SimpleLLMAgent(agent.GenerativeAgent):
  """A simple LLM agent.

  This agent keeps a history of the last observations and uses them to generate
  the next action. The action is generated by calling the model with a prompt
  that contains the agent background, the history of the last observations, and
  the call to action.

  When requesting a float action, the agent will try to parse the sampled text
  as a float. If it fails, it will return 0.0.
  """

  def __init__(
      self,
      agent_name: str,
      agent_background: str,
      model: language_model.LanguageModel,
      memories_length: int = 10,
  ):
    """Initializes the agent.

    Args:
      agent_name: The name of the agent.
      agent_background: The background intormation of the agent. This is used to
        prompt the model to engage in the roleplaying aspect of Concordia. It
        will be passed to the model at the top of the prompt when requesting an
        action.
      model: The language model to use for the agent.
      memories_length: The maximum number of memories to keep.
    """
    super().__init__()
    self._model = model
    self._agent_name = agent_name
    self._agent_background = agent_background
    self._memory = collections.deque(maxlen=memories_length)

  @functools.cached_property
  @override
  def name(self) -> str:
    return self._agent_name

  @override
  def act(
      self, action_spec: entity.ActionSpec = entity.DEFAULT_ACTION_SPEC
  ) -> str:
    previous_observations = "\n".join(self._memory)
    if action_spec.output_type == entity.OutputType.CHOICE:
      _, response, _ = self._model.sample_choice(
          f"{self._agent_background}\n"
          f"Your name is {self.name}\n"
          f"Your last observations are:\n{previous_observations}\n"
          f"{action_spec.call_to_action}\n",
          action_spec.options,
      )
      return response
    sampled_text = self._model.sample_text(
        f"{self._agent_background}\n"
        f"Your name is {self.name}\n"
        f"Your last observations are:\n{previous_observations}\n"
        f"{action_spec.call_to_action}\n"
    )
    if action_spec.output_type == entity.OutputType.FREE:
      return sampled_text
    elif action_spec.output_type == entity.OutputType.FLOAT:
      try:
        return str(float(sampled_text))
      except ValueError:
        return "0.0"
    raise NotImplementedError(
        f"Unsupported output type: {action_spec.output_type}. "
        "Supported output types are: FREE, CHOICE, and FLOAT."
    )

  @override
  def observe(
      self,
      observation: str,
  ) -> None:
    # If the memory is full, we pop the oldest memory.
    self._memory.append(observation)
